package com.net.oil.main.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.viewpager.widget.ViewPager;
import androidx.core.widget.NestedScrollView;
import
androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.base.BaseFragment;
import com.net.oil.gaode.LocationHandle;
import com.net.oil.http.AppUrl;
import com.net.oil.main.adapter.ShopBannerViewPagerAdapter;
import com.net.oil.main.adapter.ShopRecyclerViewAdapter;
import com.net.oil.main.bean.BannerShopBean;
import com.net.oil.main.bean.ShopListBean;
import com.net.oil.main.contract.ShopContract;
import com.net.oil.main.presenter.ShopPresenter;
import com.net.oil.shop.ShopDetailActivity;
import com.net.oil.util.DisplayUtil;
import com.net.oil.util.StringUtil;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.BannerViewPager;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 门店fragment
 */
public class ShopFragment extends BaseFragment<ShopPresenter> implements ShopContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.shop_recycler_view)
    RecyclerView shopRecyclerView;
    Unbinder unbinder;
    @BindView(R.id.location_tv)
    TextView locationTv;
    @BindView(R.id.location_layout)
    LinearLayout locationLayout;
    @BindView(R.id.main_banner)
    BannerViewPager mainBanner;
    @BindView(R.id.banner_dot_group)
    RadioGroup bannerDotGroup;
    @BindView(R.id.banner_layout)
    RelativeLayout bannerLayout;
    @BindView(R.id.shop_nested_scroll_view)
    NestedScrollView shopNestedScrollView;

    private ShopRecyclerViewAdapter adapter;
    private LocationHandle locationHandle;
    private AMapLocation aMapLocation;

    private City cityData;


    private int page = 1;           //当前页
    private int rows = 20;          //分页大小
    private boolean haveMore = false;

    private int carId;      //车id
    private String carType;     //车型

    public static ShopFragment newInstance() {
        return new ShopFragment();
    }

    public static ShopFragment newInstance(int carId, String carType) {
        ShopFragment fragment = new ShopFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.INTENT_CAR_ID, carId);
        bundle.putString(Constant.INTENT_CAR_TYPE, carType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLocationInfo();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop, container, false);
        unbinder = ButterKnife.bind(this, view);
        presenter = new ShopPresenter(this);
        getCarInfo();
        initView();
        initData();
        return view;
    }

    /**
     * 获取从爱车界面跳转过来的数据
     * 从ShopListActivity
     */
    private void getCarInfo() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            carId = bundle.getInt(Constant.INTENT_CAR_ID, -1);
            carType = bundle.getString(Constant.INTENT_CAR_TYPE);
        }
    }

    private void initData() {
        if (aMapLocation != null) {
            presenter.getShopList("", "", "", "", aMapLocation.getLongitude(), aMapLocation.getLatitude(), page, rows);
        } else {
            presenter.getShopList("", "", "", "", 0.00, 0.00, page, rows);
        }
        presenter.getBannerShoList();
    }


    private void initView() {
        toolbarTitle.setText(getString(R.string.shop));
        if (aMapLocation != null) {
            locationTv.setText(aMapLocation.getCity());
        }

        adapter = new ShopRecyclerViewAdapter(getContext(), carId, carType);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        shopRecyclerView.setNestedScrollingEnabled(false);
        shopRecyclerView.setLayoutManager(layoutManager);
        shopRecyclerView.setAdapter(adapter);

        /* NestedScrollView 嵌套recyclerView，加载更多需要监听NestedScrollView */
        /*shopRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //如果不能向上滚动，有更多则加载更多
                if (!shopRecyclerView.canScrollVertically(1) && haveMore && page > 1) {
                    adapter.changeMoreStatus(Constant.LOADING_MORE);
                    if (aMapLocation != null) {
                        //获取位置信息之后，根据位置获取商家
                        if (cityData != null) {
                            presenter.getShopList(cityData.getProvince(), cityData.getName(), cityData.getCounty(), "",
                                    aMapLocation.getLongitude(), aMapLocation.getLatitude(), page, rows);
                        } else {
                            presenter.getShopList("", "", "", "",
                                    aMapLocation.getLongitude(), aMapLocation.getLatitude(), page, rows);
                        }

                    } else {
                        //获取位置失败，获取商家
                        presenter.getShopList("", "", "", "",
                                0.00, 0.00, page, rows);

                    }
                }
            }
        });*/

        shopNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //判断是否滑到的底部
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    adapter.changeMoreStatus(Constant.LOADING_MORE);
                    if (aMapLocation != null) {
                        //获取位置信息之后，根据位置获取商家
                        if (cityData != null) {
                            presenter.getShopList(cityData.getProvince(), cityData.getName(), cityData.getCounty(), "",
                                    aMapLocation.getLongitude(), aMapLocation.getLatitude(), page, rows);
                        } else {
                            presenter.getShopList("", "", "", "",
                                    aMapLocation.getLongitude(), aMapLocation.getLatitude(), page, rows);
                        }

                    } else {
                        //获取位置失败，获取商家
                        presenter.getShopList("", "", "", "",
                                0.00, 0.00, page, rows);

                    }
                }
            }
        });


        locationLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (aMapLocation == null) return;
                CityPicker.getInstance()
                        .setFragmentManager(getActivity().getSupportFragmentManager())
                        .setCurrentCity(locationTv.getText().toString())
                        .setLocatedCity(new LocatedCity(aMapLocation.getCity(), aMapLocation.getProvince(), ""))
                        .setOnPickListener(new OnPickListener() {
                            @Override
                            public void onPick(int position, City data) {
                                page = 1;
                                cityData = data;
                                if (data != null) {
                                    if (!StringUtil.isEmpty(data.getName())) {
                                        locationTv.setText(data.getName());
                                    }
                                    presenter.getShopList(data.getProvince(), data.getName(), data.getCounty(), "", aMapLocation.getLongitude(), aMapLocation.getLatitude(), page, rows);
                                }
                            }

                            @Override
                            public void onLocate() {
                                //开始定位，这里模拟一下定位
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        CityPicker.getInstance().locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                                    }
                                }, 3000);
                            }
                        })
                        .show();
            }
        });

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int screenWidth = DisplayUtil.getScreenWidth();
        params.width = screenWidth;
        params.height = (int) (screenWidth / 2.3);
        mainBanner.setLayoutParams(params);

        mainBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (bannerDotGroup != null) {
                    bannerDotGroup.check(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 获取位置信息
     */
    private void initLocationInfo() {
        locationHandle = LocationHandle.getInstance();      //获取定位类的实例
        aMapLocation = locationHandle.getLastLocation();    //获取最后一次定位信息

    }

    /**
     * 获取商家列表成功
     *
     * @param shopListBean 商家列表数据
     */
    @Override
    public void getShopListSuccess(ShopListBean shopListBean) {
        dismissProgressDialog();
        if (shopListBean != null) {
            if (shopListBean.getList() != null) {

                if (page == 1) {
                    adapter.updateData(shopListBean.getList());
                } else if (page > 1) {
                    adapter.loadMore(shopListBean.getList());
                }
                if (shopListBean.getList().size() < rows) {
                    adapter.changeMoreStatus(Constant.LOADING_NONE);
                    haveMore = false;
                } else {
                    adapter.changeMoreStatus(Constant.PULL_LOAD_MORE);
                    haveMore = true;
                    page++;
                }
                if (shopListBean.getList().size() == 0) {
                    adapter.changeMoreStatus(Constant.LOADING_NONE);
                    haveMore = false;
                }
            }

        }

    }

    /**
     * 获取商家列表失败
     */
    @Override
    public void getShopListFailed() {
        dismissProgressDialog();
    }

    /**
     * 获取banner商家成功
     *
     * @param shopBeans 商家banner数据
     */
    @Override
    public void getBannerShopListSuccess(List<BannerShopBean> shopBeans) {
        setBannerView(shopBeans);
    }

    /**
     * 获取banner商家失败
     */
    @Override
    public void getBannerShopListFailed() {

    }

    private void setBannerView(List<BannerShopBean> list) {

        mainBanner.removeAllViews();
        bannerDotGroup.removeAllViews();

        if (list.size() > 0) {
            bannerLayout.setVisibility(View.VISIBLE);
            RadioGroup.LayoutParams buttonParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            buttonParams.setMargins(DisplayUtil.dip2px(5), 0,
                    DisplayUtil.dip2px(5), 0);

            List<View> views = new ArrayList<>();

            for (int i = 0; i < list.size(); i++) {

                final BannerShopBean bannerShopBean = list.get(i);

                RelativeLayout relativeLayout = new RelativeLayout(getContext());
                ImageView imageView = new ImageView(getContext());
                TextView textView = new TextView(getContext());

                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                if (!TextUtils.isEmpty(bannerShopBean.getName())){
                    textView.setText(bannerShopBean.getName());
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    textView.setTextColor(getContext().getColor(R.color.white));
                    textView.setBackgroundColor(getContext().getColor(R.color.text_color));
                    int padding = DisplayUtil.dip2px(10);
                    textView.setPadding(padding, padding, padding, padding);
                    textView.setLayoutParams(layoutParams);
                }
                relativeLayout.addView(imageView);
                relativeLayout.addView(textView);

                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                if (!StringUtil.isEmpty(bannerShopBean.getLogo())) {
                    GlideUtil.getInstance().loadImage(getContext(), imageView, AppUrl.getImageUrl(bannerShopBean.getLogo()), R.drawable.banner_err);
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ShopFragment.this.getContext(), ShopDetailActivity.class);
                        intent.putExtra(Constant.INTENT_SHOP_ID_KEY, bannerShopBean.getId());
                        intent.putExtra(Constant.INTENT_CAR_ID, carId);
                        intent.putExtra(Constant.INTENT_CAR_TYPE, carType);
                        startActivity(intent);
                    }
                });
                views.add(relativeLayout);
                //动态生成RadioButton,设置button属性
                RadioButton button = new RadioButton(getContext());
                button.setButtonDrawable(null);
                button.setLayoutParams(buttonParams);
                button.setWidth(DisplayUtil.dip2px(6));
                button.setHeight(DisplayUtil.dip2px(6));
                button.setId(i);
                button.setBackgroundResource(R.drawable.banner_dot_bg_selector);
                if (i == 0) {
                    button.setChecked(true);
                }
                bannerDotGroup.addView(button);

                //如果只有一条轮播数据，则隐藏圆点
                if (i < 1) {
                    if (bannerDotGroup.getVisibility() == View.VISIBLE) {
                        bannerDotGroup.setVisibility(View.GONE);
                    }
                } else {
                    if (bannerDotGroup.getVisibility() == View.GONE) {
                        bannerDotGroup.setVisibility(View.VISIBLE);
                    }
                }
            }

            ShopBannerViewPagerAdapter bannerViewPagerAdapter = new ShopBannerViewPagerAdapter(views);
            mainBanner.setAdapter(bannerViewPagerAdapter);
            mainBanner.setCurrentItem(0);
            mainBanner.setOffscreenPageLimit(views.size());
            mainBanner.start();
        } else {
            bannerLayout.setVisibility(View.GONE);
        }

    }
}
